using System;
using System.ComponentModel;
using System.Xml;
using System.Xml.Linq;

namespace DeclarativeTest.Core.Support
{
	public static class XmlUtil
	{
		public static string GetAttributeValue( this XElement element, XName attributeName )
		{
			XAttribute attribute = element.Attribute( attributeName );
			if( attribute == null )
				throw new XmlException( "Attribute " );
			return attribute.Value;
		}

		public static string GetAttributeValue( this XElement element, XName attributeName, string defaultValue )
		{
			XAttribute attribute = element.Attribute( attributeName );
			if( attribute == null )
				return defaultValue;
			return attribute.Value;
		}

		public static T GetAttributeValue<T>( this XElement element, XName attributeName, T defaultValue )
		{
			XAttribute attribute = element.Attribute( attributeName );
			if( attribute == null )
				return defaultValue;
			return (T)TypeDescriptor.GetConverter( typeof(T) ).ConvertFromInvariantString( attribute.Value );
		}

		public static string GetAttributeValueOrNull( this XElement element, XName attributeName )
		{
			XAttribute attribute = element.Attribute( attributeName );
			if( attribute != null )
				return attribute.Value;
			return null;
		}

		public static string GetValueFromElementOrNull( this XElement targetElement, string valueElementName )
		{
			XElement valueElement = targetElement.Element( XName.Get(valueElementName,targetElement.Name.NamespaceName) );
			if( valueElement != null )
				return valueElement.Value;
			return null;
		}

        public static XElement AddElement( this XElement element, XElement childElement )
		{
			element.Add( childElement );
            return childElement;
		}

        public static XElement AppendElement( this XElement element, XName name )
		{
            var result = new XElement(name);
            element.Add( result );
            return result;
		}
	}
}